<template>
	<div class="bar_chart" :id="idName">条形图</div>
</template>

<script setup>
import * as echarts from "echarts";
import { ref, toRefs, computed, onMounted, watch } from "vue";
import {
  paramsFun,
  $fullUrl,
  $toTime,
  $banseUrl,
  $check_action,
  $getUrlParams,
} from "@/utils/utils.js";
import { useRouter, useRoute } from "vue-router";
import storageHelper from "@/libs/StorageHelper";
let user_id = storageHelper.getUserInfo().user_id;
let router = useRouter();
const emit = defineEmits(["changeTab"]);
const props = defineProps({
  idName: {
    type: String,
    default: "barChart",
  },
  title: {
    type: String,
    default: "XXX条形图",
  },
  vm: {
    type: Object,
    default: function () {
      return {
        xAxis: "xAxis",
        names: "names",
        values: "values",
      };
    },
  },
  avg: {
    type: Boolean,
    default: false,
  },
});
let { idName, title, vm, avg } = toRefs(props);
let option=ref({
	title: {
		text: "7日个类商品销售额",
		left: "center",
	},
	tooltip: {
		trigger: 'axis',
		axisPointer: {
			type: 'shadow'
		}
	},
	legend: {
	type: 'scroll',
	orient: 'horizontal',
	y: 'bottom'
	},
	xAxis: [{
		type: 'category',
		axisTick: {
			show: false
		},
		data: []
	}],
	yAxis: [{
		type: 'value'
	}],
	series: [
		{
			data: [],
			type: 'bar'
		}
	]
})
const series = computed(() => {
	let values = vm.value.values;

	return values;
})
let init_chart = () => {
	let optionObj = option.value;

	let titleObj = title.value;
	if (titleObj) {
		optionObj.title.text = titleObj;
	}
	optionObj.series[0].data = series.value;

	let xAxis = optionObj.xAxis[0];
	xAxis.data = vm.value.xAxis;

	if (xAxis.data.length>4){
		optionObj.axisLabel= {
		interval: 0, //使x轴文字显示全
		formatter: function (params) {
			let newParamsName = '';
			const paramsNameNumber = params.length; // 文字总长度
			const provideNumber = 4; //一行显示几个字
			const rowNumber = Math.ceil(paramsNameNumber / provideNumber);
			if (paramsNameNumber > provideNumber) {
				for (let p = 0; p < rowNumber; p++) {
					const start = p * provideNumber;
					const end = start + provideNumber;
					const tempStr = p === rowNumber - 1 ? params.substring(start, paramsNameNumber) : params.substring(start, end) + '\n';
					newParamsName += tempStr;
				}
			} else {
			newParamsName = params;
			}
			return newParamsName;
			},
		}
	}
	let myChart = echarts.init(document.getElementById(idName.value));
	myChart.setOption(optionObj);
};
watch(series, (newValue, oldValue) => {
  if (newValue) {
    init_chart();
  }
});
onMounted(() => {
	setTimeout(()=>{
			init_chart();
	},200)

});
</script>
